package java_class_work.socketDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Author Tiam
 * @Date 2022/11/9 17:02
 * @Description:
 */
public class ServerThread implements Runnable {
    Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {
            serverTask();
        }
    }

    private void serverTask() {
        String nameMessage = null;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 分割读取的消息,前5位为端口号, 有目标端口号就私发, 没有作群发处理
            nameMessage = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean isPrivate = false;
        int port = 0;
        if (nameMessage.length() > 5) {
            // 类型转换问题
            port = Integer.parseInt(nameMessage.substring(0, 5));
            isPrivate = Server.map.containsKey(port);
        }
        // 如果是私发
        if (isPrivate) {
            try {
                PrintWriter pw = new PrintWriter(Server.map.get(port).getOutputStream(), true);
                pw.println(nameMessage.substring(5));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            for (Socket socket1 : Server.map.values()) {
                try {
                    System.out.println(socket1.getPort()+nameMessage);
                    PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
                    pw.println("群发消息:"+nameMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
